window.bIsMobile = false;

// 下拉子菜单（含三级）
var Multimenu = {
  mainLink : $('#top-nav-link>li'),
  subLink : $('.nav-sublink'),
  allproductsEl: $(".wrapper-nav .has-ad ul").eq(0),
    init : function(){
      var self = this;
      self.mainLink.on('mouseenter', function(e){
      $(e.currentTarget).addClass('active');
      });
      self.mainLink.on('mouseleave', function(e){
        $(e.currentTarget).removeClass('active');
      });
      $('.allproducts,.has-ad').hover(function(){
        $(".wrapper-nav .has-ad").show();
        $('.allproducts').addClass('active');
      },function(){
        $('.allproducts').removeClass('active');
        $(".wrapper-nav .has-ad").hide()
      })
       
          yhsd.ready(function(jssdk) {
              jssdk.type.get(function(data) {
                  var data = data.res.types;
                  var content = '';
                  $.each(data, function() {
                      content += '<li><a class="settings-navSubLink_color" href="/types/' + this.handle + '">' + this.name + '</a></li>';
                  });
                  self.allproductsEl.html(content);
                  if(data.length > 0){
                     $('.allproducts a').append('<i class="iconfont hoverhidden">&#xe601;</i><i class="iconfont hovershow">&#xe625;</i>');
                  }
            })
        });
        
  }
};

// 底部点击颜色变化
var MobileBarColor = {
    init:function(){
        if(/products/.test(window.location.href)){
            $(".bottombar .mobile_bar_products").addClass('active');
        }else {
            $(".bottombar li").eq(0).addClass('active');
        }
        $(".mobile_bar_list").click(function(){
          $(".bottombar .active").removeClass('active');
          $(this).addClass('active');
        })
        }
    }

// 顶部搜索
var TopSearch = {
  ico : $('#yhsd-header-search'),
  ipt : $('#yhsd-header-search-ipt'),
  init : function(){
    var self = this;
    var oIpt = self.ipt.find('input');
    //
    var sWidth = "200px";
    //
    $('#yhsd-header-search').on('click', function(){
       (function fSearchWord(){   
          var key =$('#yhsd-header-search-ipt').find('input').val();
            if(key){
              window.location.href = "/search?terms=" + encodeURIComponent(key);
            }
        })()
      });
      $('#mobile_menu #yhsd-header-search').on('click', function(){
       (function fSearchWord(){   
          var key =$('#mobile_menu #yhsd-header-search-ipt').find('input').val();
            if(key){
              window.location.href = "/search?terms=" + encodeURIComponent(key);
            }
        })()
      });

    // if(bIsMobile){
    //   sWidth = '30%';
    // }
    // self.ico.on('click', function(){
    //   oIpt.focus();
    //   self.ipt.animate({
    //     'opacity' : 1,
    //     'width' : sWidth
    //   }, 200);
    // });
    // //
    // oIpt.on('blur', function(){
    //   self.ipt.animate({
    //     'opacity' : 0,
    //     'width' : '0px'
    //   }, 200);
    // });
  }
};

// 移动导航
var Mobilenav = {
  navEl : $('#nav_mobile'),
  menuEl : $('#mobile_menu'),
  bgEl : $('#mobile_bg'),
  mobilelistEL:$('.mobile_bar_list'),
  init : function(){
    var self = this;
    var bInMenu = false;
    var bStartMove = false;
    //
    if($('html')[0].className.indexOf('ie') > -1){
        return false;
    }
    //
    $(window).on('resize', function(){
      self.menuEl.css({'left' : '-100%'});
      $('.page').css({'height' : 'auto', 'overflow' : 'auto'});
    });
    //
    var $navlist = $('.mobile_nav_menu .nav-link');
    var $arrow = $navlist.find('.post-dir-btn');
    $arrow.on('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      var $tar = $(e.currentTarget);
      var $next = $tar.parent().next();
      if($tar.hasClass('dir_off')) {
        $tar.removeClass('dir_off');
        $next.slideDown();
      } else {
        $tar.addClass('dir_off');
        $next.slideUp();
      }
    });
    //
    var fMenuOff= function(){
        bInMenu = false;
      self.bgEl.off('click', fMenuOff);
        self.menuEl.animate({
          'left' : '-100%'
        }, function(){
          $('.page').css({'height' : 'auto', 'overflow' : 'auto'});
        });
    }
    //
    self.navEl.on('click', function(){
      //
      self.menuEl.show();
      //
      self.menuEl.animate({
        'left' : '0'
      }, function(){
        var sHeight = $(window).height() + 'px';
        $('.page').css({'height' : sHeight, 'overflow' : 'hidden'});
        bInMenu = true;
      self.bgEl.on('click', fMenuOff);
      });
    });
    //
    self.mobilelistEL.on('click', function(){
      //
      self.menuEl.show();
      //
      self.menuEl.animate({
        'left' : '0'
      }, function(){
        var sHeight = $(window).height() + 'px';
        $('.page').css({'height' : sHeight, 'overflow' : 'hidden'});
        bInMenu = true;
      self.bgEl.on('click', fMenuOff);
      });
    });

    var touchSatrtFunc = function(evt){
      if(!bInMenu){
        return;
      }
      var touch = evt.touches[0]; //获取第一个触点
      var x = Number(touch.pageX); //页面触点X坐标
      self.startX = x;
      bStartMove = true;
    };


    var touchMoveFunc = function(evt){
        if(!bStartMove){
      return;
        }
        var touch = evt.touches[0];
        var x = Number(touch.pageX); //页面触点X坐标


        var nLeft = x - self.startX;
        if(nLeft < 0){
          self.leftSlide = nLeft;
          if(nLeft < -40){
            self.menuEl.css({'left' : nLeft + 'px'});
          }
        }
    };

    var touchEndFunc = function(){
      if(!bInMenu){
        return;
      }
      bStartMove = false;
      if(self.leftSlide < -80){
        fMenuOff();
      }else{
        self.menuEl.animate({
          'left' : '0'
        });
      }
    }

    document.addEventListener('touchstart', touchSatrtFunc, false);
    document.addEventListener('touchmove', touchMoveFunc, false);
    document.addEventListener('touchend', touchEndFunc, false);
  }
};

// JS SDK
// 获取当前顾客信息

var Account = {
  current: function() {
    yhsd.ready(function(sdk) {
      sdk.account.current(function(oUser){
        if(oUser.res.customer) {
          tpl1 = '<a id="customer-item1" class="header-link settings-top_color" href="/account/">' + oUser.res.customer.name + '</a>';
          tpl2 = '<a id="customer-item2" class="header-link settings-top_color" href="/account/logout">退出</a>';
          $('#customer-item1').replaceWith(tpl1);
          $('#customer-item2').replaceWith(tpl2);
          $('#customer-item3').replaceWith(tpl1);
          $('#customer-item4').replaceWith(tpl2);
        }
      });
    });
  }
}

// 橱窗按钮
var GalleryControl = {
    init: function(PCDir, MobiDir){
        // 0: horizontal
        // 1: vertical
        var PCDir = PCDir || 0,
            MobiDir = MobiDir || 0,
            self = this;

        if (self.isMobileQuery()) {
            self.act(MobiDir);
        } else {
            self.act(PCDir);
        }
        $(window).on('resize',function(){
            $('.pro-detail-gallery-list-btns').remove();

            if (self.isMobileQuery()) {
                self.act(MobiDir);
            } else {
                self.act(PCDir);
            }
        })
    },
    act: function(direction) {
        var $oMain = $('.pro-detail-gallery-main'),
            $oList = $('.pro-detail-gallery-list'),
            $oListA = $oList.children('a'),
            $oMainLength,
            $oListALength,
            nAdmissibleNumber,
            $visibleOListA = $('.pro-detail-gallery-list a:visible');


        if (direction){
            //垂直
            $oMainLength = $oMain.outerHeight(),
            $oListALength = $visibleOListA.outerHeight();

            var $oListAMarginTop = parseInt($visibleOListA.css('marginTop')),
                $oListAMarginBottom = parseInt($visibleOListA.css('marginBottom')),
                $oListAMargin = $oListAMarginTop >= $oListAMarginBottom ? $oListAMarginTop : $oListAMarginBottom;

            $oListALength += $oListAMargin;

            // 创建按钮
            var prevBtnHtml = "<span class='pro-detail-gallery-list-btns pro-detail-gallery-list-prev'><img src=''></span>";
            var nextBtnHtml = "<span class='pro-detail-gallery-list-btns pro-detail-gallery-list-next'><img src=''></span>";
        } else {
            // 水平
            $oMainLength = $oMain.outerWidth(),
            $oListALength = $visibleOListA.outerWidth();

            var $oListAMarginLeft = parseInt($visibleOListA.css('marginLeft')),
                $oListAMarginRight = parseInt($visibleOListA.css('marginRight')),
                $oListAMargin = $oListAMarginLeft + $oListAMarginRight;

            $oListALength += $oListAMargin;

            // 创建按钮
            var prevBtnHtml = "<span class='pro-detail-gallery-list-btns pro-detail-gallery-list-prev'><img src=''></span>";
            var nextBtnHtml = "<span class='pro-detail-gallery-list-btns pro-detail-gallery-list-next'><img src=''></span>";
        }

        // 可容纳的数量
        nAdmissibleNumber = parseInt($oMainLength / $oListALength);
        // 初始化显示
        $oList.find('.hidden').removeClass('hidden');

        // 橱窗图片数量不足时返回
        if ($oListA.size() <= nAdmissibleNumber) return;
        // 多余的图片隐藏
        var selector = 'a:gt(' + (nAdmissibleNumber - 1) + ')';
        $oList.children(selector).addClass('hidden');

        $oList.prepend(prevBtnHtml);
        $oList.append(nextBtnHtml);

        var $prevBtn = $('.pro-detail-gallery-list-prev');
        var $nextBtn = $('.pro-detail-gallery-list-next');

        $nextBtn.click(function() {
            $visibleOListA = $('.pro-detail-gallery-list a:visible');

            var $lastVisibleOListA = $visibleOListA.last(),
                $firstVisibleOListA = $visibleOListA.first();

            if ($oListA.index($lastVisibleOListA) == $oListA.size()-1) return;

            $firstVisibleOListA.addClass('hidden');
            $lastVisibleOListA.next('a').removeClass('hidden');

        })

        $prevBtn.click(function() {
            $visibleOListA = $('.pro-detail-gallery-list a:visible')

            var $lastVisibleOListA = $visibleOListA.last(),
                $firstVisibleOListA = $visibleOListA.first();

            if ($oListA.index($firstVisibleOListA) == 0) return;

            $firstVisibleOListA.prev('a').removeClass('hidden');
            $lastVisibleOListA.addClass('hidden');

        })
    },
    isMobileQuery: function() {
        var isMatch = false;

        if(window && window.matchMedia) {
            isMatch = window.matchMedia("screen and (max-width: 768px)").matches;
        }

        return isMatch;
    }
};

// 顶部导航显示
 (function(){
    // 滚动监听
    var _elemFather = $(document);    // 滚动条所在元素
    var elem  = _elemFather[0]
    var _eTop = $('#wrapper_header');   // Top 元素
    var _bodyOrHtml = $('body');
    var _eTopNav =  $('#wrapper_nav');
    var _eTopLogoLink = $('.wrapper-logo .logo .logo-link');
    var _eTopSlide =  $('.wrapper-slide');
    var _eTopBlog =  $('.wrapper-blog');
    var _eTopInner = $('.nav-inner-right');
    var _eTopCart = $('.mod.header');
    var _eTopCartshow = $('#yhsd_topCart');
    var _eTopsearchico = $('.header-search-ico');
    var _eTopcartico = $('#yhsd_topCart_show');
    var _eTopcsearchshow = $('.header-search');
    // 兼容性
    if(navigator.userAgent.indexOf('Trident') > -1 || navigator.userAgent.indexOf('Firefox') > -1) {
      _elemFather = $(window)
      elem  = _elemFather[0]
      _bodyOrHtml = $('html')
    }
    // 显示处理
    // var eventFn = function(e) {
    // if(_elemFather.width() >768){ 

    //   if (_elemFather.scrollTop() >= 1) { 
    //      _eTop.hide();
    //      _eTopNav.css({'top':'0'});
    //      _eTopSlide.css({'paddingTop':'48px'})
    //      _eTopInner.hide();
    //      _eTopCart.appendTo($('.wrapper-nav .cont .nav')).css({"height":"48px","line-height":"48px"});
    //      _eTopsearchico.css({"top":"5px"});
    //      _eTopCartshow.appendTo($('.wrapper-nav .cont .nav')).css({"top":"50px"});
    //      _eTopcartico.css({"top":"-4px"});
    //      _eTopcsearchshow.css({"top":"3px"});
    //   } else {
    //     _eTop.show();
    //      _eTopNav.css({'top':'82px'});
    //      _eTopSlide.css({'paddingTop':'130px'});
    //      _eTopInner.show();
    //      _eTopCart.appendTo($('.wrapper-header .cont')).css({"height":"82px","line-height":"82px"});
    //      _eTopsearchico.css({"top":"26px"});
    //      _eTopcsearchshow.css({"top":"23px"})
    //      _eTopCartshow.appendTo($('.wrapper-header .cont')).css({"top":"70px"});
    //      _eTopcartico.css({"top":"0"});

    //   }
    // }
    // };
    // 绑定滚动事件
    // _elemFather.scroll(eventFn);

  })();
// 文章列表
var postList = {
  init: function() {
    var $dirlist = $('#post-dirs-list');
    var $arrow = $dirlist.find('.post-dir-btn');
    $arrow.on('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      var $tar = $(e.currentTarget);
      var $next = $tar.parent().next();
      if($tar.hasClass('dir_off')) {
        $tar.removeClass('dir_off');
        $next.slideDown();
      } else {
        $tar.addClass('dir_off');
        $next.slideUp();
      }
    });
  }
};

var postDetail = {
  _post_count: 5,
  rePostTpl: '<a href="/posts/#{handle}" class="post-re-each settings-main_border settings-text_color"><span class="post-re-each-dot"></span>#{title}</a>',
  init: function() {
    var self = this;
    var $recentPostList = $('#post-re-list');
    yhsd.ready(function(jssdk) {
      jssdk.post.get({
        size: self._post_count + 1
      }, function(data) {
        var listInner = '';
        var rePostTpl = self.rePostTpl;
        var currentHandle = location.pathname.slice(7);
        if(data.res.code === 200 && data.res.posts.length > 1) {
          var posts = data.res.posts, i;
          for(i = 0; i < posts.length; i++) {
            // 不显示当前文章
            if(posts[i].handle != currentHandle) {
              listInner += rePostTpl.replace(/#{handle}/, posts[i].handle)
                .replace(/#{title}/, posts[i].title);
            }
          }
        } else {
          listInner = '<div class="post-re-list-tip settings-desc_color">暂无内容</div>';
        }
        $recentPostList.html(listInner);
      });
    });
  }
}


// Start Function
$(document).ready(function(){
  bIsMobile = $('body').hasClass('is_mobile');
  var oRouteCustom = {};
  oRouteCustom['all'] = function(path){
    Mobilenav.init();
    Multimenu.init();
    TopSearch.init();
    Account.current();
    $("#wechat").click(function(){
            $("#wechat-qrcode").toggleClass("show");
        });
    MobileBarColor.init();
  };
  oRouteCustom['productDetail'] = function(path){
    GalleryControl.init(1,0);
    if (!window.bIsMobile) {
      goodsShow.init();
    };
  };
  oRouteCustom['postAll'] = function(path) {
    postList.init();
  };
  oRouteCustom['postDetail'] = function(path) {
    postDetail.init(); 
  };
  $yhsd.route.init(oRouteCustom);
});
